package com.xinnet.mms.customtransfer.service.impl;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xinnet.mms.cache.memcached.MemcachedKeys;
import com.xinnet.mms.customtransfer.service.TransferRuleService;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.product.dao.ProductDao;

@Service("transferRuleService")
public class TransferRuleServiceImpl implements TransferRuleService{

/*	@Autowired(required=true)
	private MemcachedClient memcachedClient;*/

	@Autowired
	ProductDao productDao;
	/**
	 * 获取流转规则
	 */
	public List<Product> getTransferRule()throws Exception{
		//List<Product> customTransferRuleList = this.loadTransferRuleFromCache();
		List<Product> customTransferRuleList = this.loadTransferRuleFromDB();
/*		if(customTransferRuleList==null || customTransferRuleList.size()==0){
			customTransferRuleList = this.loadTransferRuleFromDB();
		}*/
		return customTransferRuleList;
	}
	
	/**
	 * 从缓存装载数据
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
/*	private synchronized List<Product> loadTransferRuleFromCache()throws Exception{
		List<Product> customTransferRuleList = (List<Product>)memcachedClient.get(MemcachedKeys.getTransferRuleKey());
		return customTransferRuleList;

	}*/
	/**
	 * 从数据库装载数据
	 * @return
	 */
	private synchronized List<Product> loadTransferRuleFromDB()throws Exception{
		List<Product> customTransferRuleList = (List<Product>)productDao.queryEnableProduct();
		if (customTransferRuleList==null || customTransferRuleList.isEmpty()){
			return null;
		}
		return customTransferRuleList;
	}
	
/*	public void addTransferRule(List<Product> productList) throws TimeoutException, InterruptedException, MemcachedException{
		for (Iterator<Product> iterator = productList.iterator(); iterator.hasNext();) {
			Product product = (Product) iterator.next();
			productDao.addProduct(product);	
		}	
		memcachedClient.delete(MemcachedKeys.getTransferRuleKey());
	}
	
	public void delTransferRuleByProductName(String productName) throws TimeoutException, InterruptedException, MemcachedException{
		productDao.delTransferRuleByProductName(productName);
		memcachedClient.delete(MemcachedKeys.getTransferRuleKey());
	}*/
}
